﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using Common;
using Basic.Model.Entity;
using Basic.Model.EntityManager;

namespace Basic.Business
{
    public class MenuNodeAdmin
    {
        #region 往菜单目录中添加一个新的菜单
        public static void AddMenuNode(string parentMenuName, string menuName, int menuOrderNumber, string menuUrl, string menuRoleKey)
        {
            ISession session = null;
            MenuNode menuNode = null;
            try
            {
                session = NHibernateHelper.OpenSession();
                menuNode = new MenuNode();
                menuNode.menuName = menuName;
                menuNode.menuOrderNumber = menuOrderNumber;
                menuNode.menuUrl = menuUrl;
                menuNode.roleKey = menuRoleKey;
                if (String.IsNullOrEmpty(parentMenuName))
                    menuNode.menuParentId = 0;
                else
                    menuNode.menuParentId = MenuNodeManager.GetByCondition(session, parentMenuName).menuId;
                MenuNodeManager.Add(session, menuNode);
                session.Flush();
            }
            catch
            {
                throw;
            }
            finally
            {
                if (session != null)
                    session.Close();
            }
        }
        #endregion
        #region 获取所有菜单的按照树形目录排序的列表
        public static IList<MenuNode> GetAllByTree()
        {
            ISession session = null;
            ITransaction trans = null;
            IList<MenuNode> list = null;
            IList<MenuNode> list1 = new List<MenuNode>();
            try
            {
                session = NHibernateHelper.OpenSession();
                trans = session.BeginTransaction();
                list = MenuNodeManager.GetAll(session);
                trans.Commit();
            }
            catch
            {
                if (trans != null)
                    trans.Rollback();
                throw;
            }
            finally
            {
                if (session != null)
                    session.Close();
            }
            FillChildMenuNode(list, list1, 0);
            return list1;
        }

        private static void FillChildMenuNode(IList<MenuNode> list, IList<MenuNode> list1, int menuParentId)
        {
            foreach (MenuNode menuNode in list)
            {
                if (menuNode.menuParentId == menuParentId)
                {
                    list1.Add(menuNode);
                    FillChildMenuNode(list, list1, menuNode.menuId);
                }
            }
        }
        #endregion
    }
}
